package org.apache.ocean.snapshot;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.ocean.CElement;
import org.apache.ocean.CLong;
import org.apache.ocean.XMLUtil;
import org.jdom.Element;

public class Snapshot implements CElement {
	public Map<String,SnapshotFile> files = new HashMap<String,SnapshotFile>();
	public Date timestamp;
	public String name;

	public Snapshot() {

	}
	
	public void add(SnapshotFile snapshotFile) {
		files.put(snapshotFile.name, snapshotFile);
	}

	public Element toElement() throws Exception {
    Element root = new Element("snapshot");
    XMLUtil.setAttribute("name", name, root);
    XMLUtil.setAttribute("timestamp", timestamp, root);
    for (SnapshotFile snapshotFile : files.values()) {
    	root.addContent(snapshotFile.toElement());
    }
    return root;
	}

	public Snapshot(Element root) throws Exception {
		name = XMLUtil.getAttributeString("name", root);
		timestamp = XMLUtil.getAttributeDate("timestamp", root);
		for (Element element : XMLUtil.getChildren("file", root)) {
			add(new SnapshotFile(element));
		}
	}

	public static class SnapshotFile implements CElement {
		public CLong lastModified;
		public String name;
		public CLong size;
    
		public SnapshotFile() {}
		
		public SnapshotFile(Element root) throws Exception {
			lastModified = XMLUtil.getAttributeLong("lastModified", root);
			size = XMLUtil.getAttributeLong("size", root);
			name = root.getAttributeValue("name");
		}
		
		public Element toElement() throws Exception {
			Element element = new Element("file");
			XMLUtil.setAttribute("name", name, element);
			XMLUtil.setAttribute("lastModified", lastModified, element);
			XMLUtil.setAttribute("size", size, element);
			return element;
		}
	}
}
